package com.njupt.swg.service;

import com.njupt.swg.mapper.TbContentCategoryMapper;
import com.njupt.swg.pojo.EasyUITreeNode;
import com.njupt.swg.pojo.TaotaoResult;
import com.njupt.swg.pojo.TbContentCategory;
import com.njupt.swg.pojo.TbContentCategoryExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {
    @Autowired
    private TbContentCategoryMapper contentCategoryMapper;

    @Override
    public List<EasyUITreeNode> getContentCategoryList(long parentId) {
        TbContentCategoryExample example = new TbContentCategoryExample();
        TbContentCategoryExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        List<TbContentCategory> list = contentCategoryMapper.selectByExample(example);

        List<EasyUITreeNode> easyUITreeNodeList = new ArrayList<>();
        for(TbContentCategory contentCategory:list){
            EasyUITreeNode easyUITreeNode = new EasyUITreeNode();
            easyUITreeNode.setId(contentCategory.getId());
            easyUITreeNode.setText(contentCategory.getName());
            easyUITreeNode.setState(contentCategory.getIsParent()?"closed":"open");
            easyUITreeNodeList.add(easyUITreeNode);
        }
        return easyUITreeNodeList;
    }

    @Override
    public TaotaoResult addContentCategory(Long parentId, String name) {
        TbContentCategory contentCategory = new TbContentCategory();
        contentCategory.setParentId(parentId);
        contentCategory.setName(name);
        contentCategory.setCreated(new Date());
        contentCategory.setUpdated(new Date());

        contentCategory.setIsParent(false);//不是父节点
        contentCategory.setStatus(1);//正常为1
        contentCategory.setSortOrder(1);//默认为1

        contentCategoryMapper.insertSelective(contentCategory);

        //更新父节点的状态
        TbContentCategory parentContentCategory = contentCategoryMapper.selectByPrimaryKey(parentId);
        if(parentContentCategory!=null && !parentContentCategory.getIsParent()){
            parentContentCategory.setIsParent(true);
            contentCategoryMapper.updateByPrimaryKeySelective(parentContentCategory);
        }
        return TaotaoResult.ok(contentCategory);
    }
}
